﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data;
using DevExpress.Utils;
using System.Threading;

namespace TaxiDispatchClient
{
    public partial class TaxiStateStatisticsForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiStateStatisticsForm()
        {
            InitializeComponent();
            CurrencyDataController.DisableThreadingProblemsDetection = true;
        }
        private void TaxiStateStatisticsForm_Load(object sender, EventArgs e)
        {                      
            string strSql = "DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= Updatetime ";//date(Updatetime)= '2012-03-16'
            if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
            {
                strSql += " and CompanyName = '" +
                          MainForm.MyUserInfo.CompanyName + "'";                
            }
            DataSet ds = MainForm.PositionService.TaxiGpsHistoryGetStatisticsList(strSql);
            _dt = ds.Tables[0];
            _dt.Columns.Add("PageIndex", typeof (int));
            PageForDt();
            _dtCurrentPage = _dt.Clone();
            //_dtCurrentPage.Rows.Clear();
            //gridControl1.DataSource =_dtCurrentPage;          
            //将第一页数据绑定               
            _dtCurrentPage.Rows.Clear();            
            foreach (DataRow row in _dt.Select("PageIndex = " + _currentPage))
            {            
                DataRow newrow = _dtCurrentPage.NewRow();
                newrow.ItemArray = row.ItemArray;
                _dtCurrentPage.Rows.Add(newrow);
            }
            gridControl1.DataSource = _dtCurrentPage;
            //label_currentPage.Text = (_currentPage + 1).ToString();            
            dateEdit1.DateTime = DateTime.Now;
            _isLoad = false;
            //label_currentPage.Text = (_currentPage+1).ToString();
            label_totalPage.Text = (_pageCount).ToString();
            if (_pageCount > 0)
                label_currentPage.Text = (_currentPage + 1).ToString();
            else label_currentPage.Text = "0";
             #region 设置gridControl1的样式
            gridView1.GroupPanelText = "载客率/空载率统计";
            gridView1.RowHeight = 25;
            gridView1.OptionsBehavior.Editable = false;
            gridView1.Columns["PageIndex"].Visible = false;                                                           
            gridView1.Columns["TaxiNo"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["TaxiNo"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["TaxiNo"].Caption = "出租车牌照";
            gridView1.Columns["NoPsgPerts"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["NoPsgPerts"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["NoPsgPerts"].Caption = "空载率(%)";
            gridView1.Columns["CarryPsgPerts"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["CarryPsgPerts"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["CarryPsgPerts"].Caption = "载客率(%)";
            gridView1.Columns["OtherPerts"].AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["OtherPerts"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gridView1.Columns["OtherPerts"].Caption = "其他(%)";            
              #endregion

        }
        private DataTable _dt;            //总表 用于存放所有出租车信息 添加了载客率 空载率的列
        private DataTable _dtCurrentPage; //子表 作为当前页面gridview的数据源
        private Thread _threadCount;      //用来计算当前页面内的出租车的载客率、空载率
        private const int PageSize = 15; //gridview每页数据条数
        private int _pageCount = 0;      //出租车总表总页数
        private int _currentPage = 0;   //当前gridview中为第几页
        private bool _isLoad = true;   //标记是否是页面加载
       
        
        private void comboBoxEdit_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxEdit_type.SelectedIndex == 0)
            {
                dateEdit1.DateTime = DateTime.Now;
            }
            if (_threadCount != null && _threadCount.IsAlive)
            {
                _threadCount.Abort();
                _dtCurrentPage.Rows.Clear();
            }
            _threadCount = new Thread(GetCurrentPageRows);
            _threadCount.Start(_currentPage);            
        }

        private void btn_prev_Click(object sender, EventArgs e) //上一页
        {
            if (_currentPage>0)
            {
                _currentPage--;           
                _dtCurrentPage.Rows.Clear();
                int count = 0;
                foreach (DataRow row in _dt.Select("PageIndex = " + _currentPage))
                {
                    count++;
                    DataRow newrow = _dtCurrentPage.NewRow();
                    newrow.ItemArray = row.ItemArray;
                    _dtCurrentPage.Rows.Add(newrow);
                }
                gridControl1.DataSource = _dtCurrentPage;
                label_currentPage.Text = (_currentPage + 1).ToString();
            }
        }

        private void btn_next_Click(object sender, EventArgs e) //下一页
        {            
            if (_currentPage < _pageCount - 1)
            {
                _currentPage++;
                _dtCurrentPage.Rows.Clear();
                int count = 0;
                foreach (DataRow row in _dt.Select("PageIndex = " + _currentPage))
                {
                    count++;
                    DataRow newrow = _dtCurrentPage.NewRow();
                    newrow.ItemArray = row.ItemArray;
                    _dtCurrentPage.Rows.Add(newrow);
                }
                gridControl1.DataSource = _dtCurrentPage;
            }
            label_currentPage.Text = (_currentPage + 1).ToString();
        }

       #region 加载前页面内的出租车的空载率、载客率
        private void GetCurrentPageRows(object page)
        {
            int pageindex = (int)page;        
            DateTime date = dateEdit1.DateTime;          
            StringBuilder strSql = new StringBuilder("");
            switch (comboBoxEdit_type.SelectedIndex)
            {
                case 0: 
                    strSql.Append(" DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= Updatetime");
                    break;
                case 1: 
                    strSql.Append(" date(Updatetime)= '");
                    strSql.Append(date.Date);
                    strSql.Append("'");
                    break;
                case 2: 
                     DateTime monday = GetFirstAndLastDayOfOneWeek(date)[0];
                    DateTime sunday = GetFirstAndLastDayOfOneWeek(date)[1];
                    strSql.Append(" (Updatetime Between '");
                    strSql.Append(monday.Date);
                    strSql.Append("' and '");
                    strSql.Append(sunday);
                    strSql.Append("')");
                    break;
                case 3: 
                      DateTime firstday = date.AddDays(-date.Day + 1);
                    DateTime nextmonth = firstday.AddMonths(1);
                    DateTime lastday = nextmonth.AddDays(-1);
                    strSql.Append(" (Updatetime Between '");
                    strSql.Append(firstday.Date);
                    strSql.Append("' and '");
                    strSql.Append(lastday);
                    strSql.Append("')");
                    break;            
            }

            if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
            {
                strSql.Append(" and CompanyName='");
                strSql.Append(MainForm.MyUserInfo.CompanyName);
                strSql.Append("'");
            }

            lock (_dt)
            {
                try
                {
                    _dt = MainForm.PositionService.TaxiGpsHistoryGetStatisticsList(strSql.ToString()).Tables[0];
                }
                catch (Exception ex)
                {
                }
                _dt.Columns.Add("PageIndex", typeof(int));
                PageForDt();    
            }            
            _dtCurrentPage.Rows.Clear();
            int count = 0;
            foreach (DataRow row in _dt.Select("PageIndex = " + pageindex))
            {             
                count++;
                DataRow newrow = _dtCurrentPage.NewRow();
                newrow.ItemArray = row.ItemArray;
                _dtCurrentPage.Rows.Add(newrow);
            }
            gridControl1.DataSource = _dtCurrentPage;
        }
        #endregion

      
       #region 将_dt数据分页,更新总页数
        private void PageForDt()
        {
            if (_dt.Rows.Count > 0)
            {                           
                for (int i = _dt.Rows.Count -1; i >=0; i--)
                {
                    DataRow row = _dt.Rows[i];
                    if (row["TaxiNo"] == null || row["TaxiNo"].ToString() == "")
                    {
                        _dt.Rows.RemoveAt(i);
                    }
                }
                
                int flag = 0;
                int pageindex = 0;
                for (int i = 0; i < _dt.Rows.Count; i++)
                {

                    if (flag < PageSize)
                    {
                        _dt.Rows[i]["PageIndex"] = pageindex;
                        flag++;
                    }
                    else
                    {
                        flag = 1;
                        pageindex++;
                        _dt.Rows[i]["PageIndex"] = pageindex;
                    }
                }
                _pageCount = pageindex + 1;
                BeginInvoke(new MethodInvoker(() =>
                    {
                        label_currentPage.Text = (_currentPage + 1).ToString();
                        label_totalPage.Text = (_pageCount).ToString();            
                    }));
            }
        }
#endregion

       
       private enum StatisticsEnum //统计类型 按天、周、月、最近一周统计
        {
            ByDay,
            ByWeek,
            ByMonth,   
            ByLastWeek //最近一周
        }

        //得到指定日期所在的一个星期的 星期一和星期天
        private DateTime[] GetFirstAndLastDayOfOneWeek(DateTime date) 
        {
            DateTime monday = date;
            DateTime sunday = date;
            switch (date.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    monday = date;
                    sunday = date.AddDays(6);
                    break;
                case DayOfWeek.Tuesday:
                    monday = date.AddDays(-1);
                    sunday = date.AddDays(5);
                    break;
                case DayOfWeek.Wednesday:
                    monday = date.AddDays(-2);
                    sunday = date.AddDays(4);
                    break;
                case DayOfWeek.Thursday:
                    monday = date.AddDays(-3);
                    sunday = date.AddDays(3);
                    break;
                case DayOfWeek.Friday:
                    monday = date.AddDays(-4);
                    sunday = date.AddDays(2);
                    break;
                case DayOfWeek.Saturday:
                    monday = date.AddDays(-5);
                    sunday = date.AddDays(1);
                    break;
                case DayOfWeek.Sunday:
                    monday = date.AddDays(-6);
                    sunday = date;
                    break;
            }
            DateTime[] firstLastDay = {monday, sunday};
            return firstLastDay;
        }



        private void TaxiStateStatisticsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_threadCount != null && _threadCount.IsAlive)
            {
                _threadCount.Abort();
                _dtCurrentPage.Rows.Clear();
            }
        }

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void TaxiStateStatisticsForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Close();
            }
        }      

#endregion

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (!_isLoad)
            {
                
                if (comboBoxEdit_type.SelectedIndex==0 &&
                    dateEdit1.DateTime.Date != DateTime.Today)
                {
                    comboBoxEdit_type.SelectedIndex = 1;
                }
                
                else
                {
                    if (_threadCount != null && _threadCount.IsAlive)
                    {
                        _threadCount.Abort();
                        _dtCurrentPage.Rows.Clear();
                    }
                    _threadCount = new Thread(GetCurrentPageRows);
                    _threadCount.Start(_currentPage);                        
                }                
            }           
        }

     
    }
}